<?php

namespace addon\lian\model;

use addon\lian\model\sqlmodel\GoodsSkuModel;
use addon\lian\model\sqlmodel\LianGoodsModel;
use addon\lian\model\sqlmodel\LianLevelModel;
use app\model\BaseModel;
use addon\lian\model\sqlmodel\GoodsModel;
use think\facade\Db;
use think\facade\Log;

/**
 * 链动商品  addon\lian\model\LianGoods
 */
class LianGoods extends BaseModel
{

    /**
     * 修改链动商品
     * @param $data
     * @param $condition
     * @return array
     */
    public function editGoodsLian($data, $condition)
    {
        $re = model('goods')->update($data, $condition);
        return $this->success($re);
    }


    /**
     * 获取商品列表
     * @param array $where
     * @return array
     */
    public function getPage(array $condition, $site_id, $page_index, $page_size)
    {
        $field = 'goods_id,site_id,goods_name,goods_class,goods_image,goods_stock,sale_num,sort,create_time,goods_state';
        $order = 'create_time desc';
        $sku_where = [
            // ['goodsSku.is_default', '=', 1],
            ['goods.site_id', '=', $site_id],
        ];

        $search_model = (new GoodsModel())->alias('goods')
            ->where($condition)
            // ->withSearch(["goods_name", "goods_type", "goods_category"], $where)
            ->field($field)
            ->with([
                'goodsSku' => function ($query) {
                    $query->withField('sku_id, goods_id, price, is_default');
                },
                // 'goodsSku' => ['sku_id','goods_id','price']
            ])
            ->where($sku_where)
            ->order($order)->append(['goods_edit_path', 'goods_cover_thumb_small']);

        $list = $search_model->paginate([
            'list_rows' => $page_size,
            'page' => $page_index
        ]);

        $result = [];
        foreach ($list->items() as &$value) {
            $data = $value->toArray();
            $info = (new LianGoodsModel())->where([['site_id', '=', $site_id], ['goods_id', '=', $value['goods_id']]])->findOrEmpty()->toArray();

            if (empty($info)) {
                $data['is_lian'] = 0;
            }else{
                $data['is_lian'] = $info['is_lian'];
            }
            $result[] = $data;
        }

        return [
            'code' => 0,
            'message' => 'SUCCESS',
            'data' => [
                'count' => $list->total(),
                'list' => $result,
                'page' => $page_index,
                'page_size' => $page_size
            ]
        ];
    }


    /**
     * 修改链动商品
     * @param int $goods_id
     * @param $data
     */
    public function editLianGoods(int $goods_id, $data, $site_id)
    {
        try {
            $lianGoods = [
                'is_lian' => $data['is_lian'],
                'is_rule' => $data['is_rule'],
            ];
            
            // 处理reward_set
            if (!empty($data['reward_set'])) {
                // 如果reward_set是字符串，先解码
                if (is_string($data['reward_set'])) {
                    $reward_set = json_decode($data['reward_set'], true);
                } else {
                    $reward_set = $data['reward_set'];
                }
                
                // 处理reward_set数据，确保比例和金额的互斥性
                if (is_array($reward_set) && !empty($reward_set)) {
                    foreach ($reward_set as $sku_id => &$sku_reward) {
                        if (is_array($sku_reward)) {
                            foreach ($sku_reward as $level_id => &$level_reward) {
                                if (is_array($level_reward) && !is_numeric($level_id)) {
                                    // 处理直推奖
                                    if (!empty($level_reward['recommend_rate']) && $level_reward['recommend_rate'] > 0) {
                                        $level_reward['recommend_money'] = '0';
                                    }
                                    
                                    // 处理见点奖
                                    if (!empty($level_reward['see_rate']) && $level_reward['see_rate'] > 0) {
                                        $level_reward['see_money'] = '0';
                                    }
                                    
                                    // 处理感恩奖
                                    if (!empty($level_reward['cultivate_rate']) && $level_reward['cultivate_rate'] > 0) {
                                        $level_reward['cultivate_money'] = '0';
                                    }
                                }
                            }
                            unset($level_reward);
                        }
                    }
                    unset($sku_reward);
                    
                    $lianGoods['reward_set'] = json_encode($reward_set, JSON_UNESCAPED_UNICODE);
                } else {
                    $lianGoods['reward_set'] = '';
                }
            } else if (!empty($data['skuList'])) {
                // 旧逻辑保留，处理skuList
                foreach ($data['skuList'] as $value) {
                    if (isset($value['sku_id']) && isset($value['calculate_price'])) {
                        $data['reward_set'][$value['sku_id']]['calculate_price'] = $value['calculate_price'];
                    }
                }
                if (is_array($data['reward_set']) && !empty($data['reward_set'])) {
                    $lianGoods['reward_set'] = json_encode($data['reward_set'], JSON_UNESCAPED_UNICODE);
                } else {
                    $lianGoods['reward_set'] = '';
                }
            } else {
                $lianGoods['reward_set'] = '';
            }
    
            // 查询是否已存在记录
            $info = (new LianGoodsModel())->where([['site_id', '=', $site_id], ['goods_id', '=', $goods_id]])->findOrEmpty()->toArray();
            if (empty($info)) {
                // 新增
                $lianGoods['site_id'] = $site_id;
                $lianGoods['goods_id'] = $goods_id;
                (new LianGoodsModel())->create($lianGoods);
            } else {
                // 更新
                (new LianGoodsModel())->where([['goods_id', '=', $goods_id], ['site_id', '=', $site_id]])->update($lianGoods);
            }
    
            return $this->success('success');
        } catch (\Throwable $th) {
            Log::error('修改链动商品失败: ' . $th->getMessage() . '--line:' . $th->getLine() . '--file:' . $th->getFile());
            return $this->error('修改失败');
        }
    }


    public function modifyGoodsIsLian($goods_ids, int $is_lian, int $site_id)
    {
        try {
            $lian_goods_list = (new LianGoodsModel())->where([['site_id', '=', $site_id], ['goods_id', 'in', $goods_ids]])
            ->with([
                'skuList' => function ($query) {
                    $query->field('sku_id, goods_id, price,sku_name');
                },
            ])
            ->select()->toArray();

            if (!empty($lian_goods_list)) {
                $lian_goods_id_list = array_column($lian_goods_list, 'goods_id');
            } else {
                $lian_goods_id_list = [];

            }

            $lian_goods_list = (new GoodsModel())->where([['site_id', '=', $site_id], ['goods_id', 'in', $goods_ids]])
                ->with([
                    'skuList' => function ($query) {
                        $query->field('sku_id, goods_id, price,sku_name,cost_price');
                    },
                ])
                ->select()->toArray();

            //添加执行
            $goods_id_array = $goods_ids;

            //查询链动等级
            $LevelModel = new LianLevelModel();
            $levelList = $LevelModel->field('level_id,level_name,level_num,recommend_rate,see_rate,cultivate_rate')->where([['site_id', '=', $site_id]])->order('level_num asc')->select()->toArray();
            
            $skuList = [];
            $goods_rule = [];
            foreach ($lian_goods_list as $key => $value) {
                $skuList[] = $value['skuList'];
            }
            $result = array_reduce($skuList, function ($result, $value) {
                return array_merge($result, array_values($value));
            }, array());
            foreach ($result as $key => &$value) {
                $value['calculate_price'] = '';
                $goods_rule[$value['sku_id']] = $value;
            }
            foreach ($goods_rule as &$value) {
                foreach ($levelList as $val) {
                    $val['recommend_money'] = '0';
                    $val['see_money'] = '0';
                    $val['cultivate_money'] = '0';
                    $value[$val['level_id']] = $val;
                    $value[$val['level_num']] = $val;
                }
            }
            $result = array_reduce($goods_rule, function ($carry, $item) {
                if (!isset($carry[$item['goods_id']])) {
                    $carry[$item['goods_id']] = [];
                }
                $carry[$item['goods_id']][$item['sku_id']] = $item;
                return $carry;
            }, []);

            // foreach ($lian_goods_list as $val) {
            //     $val['rate'] = '0';
            // }

            foreach ($goods_id_array as $k => $v) {

                if (!in_array(intval($v), $lian_goods_id_list)) {
                    //添加
                    (new LianGoodsModel())->create(['goods_id' => $v, 'site_id' => $site_id, 'is_rule' => 1, 'reward_set' => json_encode($result[$v])]);
                }

            }
            //整体执行
            (new LianGoodsModel())->where([['site_id', '=', $site_id], ['goods_id', 'in', $goods_ids]])->update(['is_lian' => $is_lian]);
            return $this->success('success');
        } catch (\Throwable $th) {
            Log::error('修改链动商品失败: ' . $th->getMessage() . '--line:' . $th->getLine() . '--file:' . $th->getFile());
            return $this->error('修改失败');
        }
        
    }

    /**
     * Summary of getGoodsCommission
     * @param mixed $goods_id
     * @throws \think\db\exception\DbException
     * @return array{goods_info: mixed, rule: mixed}
     */
    public function getGoodsCommission($goods_id, $site_id)
    {
        //获取商品信息
        $field = 'goods_id,site_id,goods_name,goods_type,goods_cover,stock,sale_num,status,sort,create_time';

        $goodsInfo = (new GoodsModel())->where([['site_id', '=', $site_id], ['goods_id', '=', $goods_id]])
            ->field($field)
            ->with([
                'lianGoods' => function ($query) {
                    $query->withField('goods_id, is_rule, reward_set, is_lian');
                },
                'skuList' => function ($query) {
                    $query->field('sku_id, goods_id, price,sku_name,cost_price');
                },
            ])
            ->append(['goods_type_name', 'goods_edit_path', 'goods_cover_thumb_small'])->findOrEmpty();
        if (!$goodsInfo->isEmpty()) {
            $goodsInfo = $goodsInfo->toArray();
            if (empty($goodsInfo['lianGoods'])) {
                $goodsInfo['is_set_lian'] = 0;
                $goodsInfo['is_rule'] = 1;
            } else {

                $goodsInfo['is_set_lian'] = $goodsInfo['lianGoods']['is_lian'];
                $goodsInfo['is_rule'] = $goodsInfo['lianGoods']['is_rule'];
            }

            //查询链动等级
            $lianLevelModel = new LianLevelModel();
            $levelList = $lianLevelModel->field('level_id,level_name,level_num,see_rate,recommend_rate,cultivate_rate')->where([['site_id', '=', $this->site_id]])->order('level_num asc')->select()->toArray();
            if (!empty($goodsInfo['lianGoods'])) {
                foreach ($goodsInfo['lianGoods']['reward_set'] as &$value) {

                    foreach ($levelList as $val) {
                        if (!isset($value[$val['level_id']])) {
                            $value[$val['level_id']]['level_name'] = $val['level_name'];
                            $value[$val['level_id']]['level_id'] = $val['level_id'];
                            $value[$val['level_id']]['level_num'] = $val['level_num'];
                            $value[$val['level_id']]['recommend_rate'] = $val['recommend_rate'];
                            $value[$val['level_id']]['see_rate'] = $val['see_rate'];
                            $value[$val['level_id']]['cultivate_rate'] = $val['cultivate_rate'];
                            $value[$val['level_id']]['recommend_money'] = '0';
                            $value[$val['level_id']]['see_money'] = '0';
                            $value[$val['level_id']]['cultivate_money'] = '0';
                        }
                    }
                }
                //追加链动计算金额
                foreach ($goodsInfo['skuList'] as &$value) {
                    $temp_lian_goods_rule = $goodsInfo['lianGoods']['reward_set'][$value['sku_id']] ?? [];
                    $value['calculate_price'] = $temp_lian_goods_rule['calculate_price'] ?? '';
                }

                $goodsInfo['lianGoods']['reward_set'] = json_encode($goodsInfo['lianGoods']['reward_set']);
            } else {

                $goodsInfo['lianGoods'] = [
                    'goods_id' => $goods_id,
                    'is_rule' => 1,
                    'reward_set' => [],
                    'is_lian' => 0
                ];
                foreach ($goodsInfo['skuList'] as &$value) {
                    $value['calculate_price'] = '';
                }
            }

            $data = [
                'goods_info' => $goodsInfo,
                'rule' => $levelList
            ];
            return $data;
        } else {
            throw new \think\db\exception\DbException('LY_LIAN_NOT_FOUND_GOODS');
        }

    }


    public function getLianGoodsIds($site_id){
        $list = (new LianGoodsModel())->where([
            ['site_id', '=', $site_id], ['is_lian', '=', 1]
        ])->column('goods_id');
        
        return $list;
    }

    
}
